package com.fly.socket.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.fly.socket.po.Message;
import com.fly.socket.po.User;
import com.fly.socket.service.LoginService;
import com.fly.socket.websocket.MyWebSocketHandler;
import com.google.gson.GsonBuilder;

@RestController
public class ChatController
{
    @Autowired
    MyWebSocketHandler handler;
    
    @Autowired
    LoginService loginservice;
    
    @Autowired
    HttpSession session;
    
    /**
     * 获取在线用户
     * 
     * @return
     * @see [类、类#方法、类#成员]
     */
    @PostMapping("/onlineusers")
    public Set<String> onlineusers()
    {
        Map<Long, WebSocketSession> map = MyWebSocketHandler.USER_SOCKET_SESSION_MAP;
        Set<Long> set = map.keySet();
        Iterator<Long> it = set.iterator();
        Set<String> nameset = new HashSet<String>();
        while (it.hasNext())
        {
            Long entry = it.next();
            String name = loginservice.getnamebyid(entry);
            String user = (String)session.getAttribute("username");
            if (!user.equals(name))
            {
                nameset.add(name);
            }
        }
        return nameset;
    }
    
    /**
     * 发布系统广播（群发）
     * 
     * @param text
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    @PostMapping("broadcast")
    public void broadcast(@RequestParam String text)
        throws IOException
    {
        Message msg = new Message();
        msg.setDate(new Date());
        msg.setFrom(-1L);// -1表示系统广播
        msg.setFromName("系统广播");
        msg.setTo(0L);
        msg.setText(text);
        handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
    }
    
    /**
     * 获取用户Id
     * 
     * @param username
     * @return
     * @see [类、类#方法、类#成员]
     */
    @PostMapping("/getuid")
    public User getuid(@RequestParam String username)
    {
        Long uid = loginservice.getUidbyname(username);
        User user = new User();
        user.setUid(uid);
        return user;
    }
}
